import Vue from 'vue'
import Router from 'vue-router'
import store from "../store/index";

import Layout from '@/views/layout/Layout';

Vue.use(Router);

// 页面刷新时，重新赋值token
if (sessionStorage.getItem('token')) {
  store.commit('SET_TOKEN', sessionStorage.getItem('token'))
}

let router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/login',
      name: '登录',
      meta: {auth: false},
      // 模块使用异步加载
      component: (resolve) => require(['@/views/login'], resolve)
    },
    {
      path: '/',
      name: '主页',
      component: Layout,
      meta: {auth: true},
      hidden: true,
      redirect: '/dashboard',
      children: [{
        path: 'dashboard',
        component: () => import('@/views/dashboard/index')
      }]
      // 模块使用异步加载
    },
    {
      path: '/404',
      name: '404',
      meta: {auth: false},
      component: () => import('@/views/404')
      // 模块使用异步加载

    }
  ],
  scrollBehavior: () => ({y: 0})
});
//拦截登录，token验证
//路由验证这个方法函数和vue实例的顺序还有关系，如果写在vue后面，下面才会执行，后判断
router.beforeEach((to, from, next) => {
/*  if (store.state.login.token) {
    if (to.path !== '/login') {
      next({path: '/login'})
    } else {
      if (store.state.login.info.length === 0) {
        try {
          store.dispatch('GET_INFO').then(data => {
            console.log(222222);
          });
        } catch (err) {

        }

      }
      next();
    }
  }*/
    if (to.meta.auth && !store.state.login.token && to.path !== '/login') {
      return next({
        path: '/login',
        query: {redirect: to.fullPath}
      })
    } else {

    }
    next();
});
export default router;
